package com.warm.netty;

import cn.hutool.core.lang.UUID;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.nio.charset.Charset;
import java.util.Calendar;
import java.util.Date;

/**
 * netty服务端处理器
 **/
@Slf4j
@Component
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
    // 需调用的service，根据自身进行修改
    // @Autowired
    // private EquipmentManagementService equipmentManagementService;

    public NettyServerHandler() {
    }

    private static NettyServerHandler nettyServerHandler;

    // @PostConstruct该注解被用来修饰一个非静态的void（）方法。被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,PostConstruct在构造函数之后执行，init（）方法之前执行。
    @PostConstruct
    public void init() {
        nettyServerHandler = this;
        // nettyServerHandler.equipmentManagementService = this.equipmentManagementService;
    }

    /**
     * 客户端连接会触发
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("客户端正在请求.......");
    }

    /**
     * 客户端发消息会触发
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.info("服务器收到消息: {}", msg);
        String s = objectToHexStr(msg);
        log.info("服务器收到消息s: {}", s);
        // 有一些设备在服务器收到信息之后需要回传一份要求的数据，具体回传如下
        Calendar feedBack = Calendar.getInstance();
        ByteBuf bff = Unpooled.buffer(9);

        bff.writeBytes("接受成功!".getBytes());
        ctx.writeAndFlush(bff);
        log.info("服务器收到消息结束");
    }

    private static String objectToHexStr(Object msg) {
        ByteBuf buf = (ByteBuf) msg;
        byte[] bytes = new byte[buf.readableBytes()];
        buf.readBytes(bytes);//复制内容到字节数组bytes
        return new String(bytes, Charset.defaultCharset());//将接收到的数据转为字符串，此字符串就是客户端发送的字符串
    }
}

